package com.example.demo.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.cfg.MapperConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.xml.transform.Result;
import java.sql.ResultSet;
import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * Description: 统一数据返回格式
 */
@ControllerAdvice
@ResponseBody
public class ResponseAdvice2 implements ResponseBodyAdvice {

    /**
     * 控制器（开关）：当返回 false 时，项目不会对数据返回格式进行统一处理
     * 如果为 true，表示开启数据返回格式统一处理，执行下面的 beforeBodyWrite
     * @param returnType
     * @param converterType
     * @return
     */
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    // 操作 jackson 的工具
    // Spring Boot内置了 Jackson
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 自定义统一处理返回数据格式
     * @param body 原始的数据返回结果
     * @param returnType
     * @param selectedContentType
     * @param selectedConverterType
     * @param request
     * @param response
     * @return 返回 新的 body
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 这里选择返回 json 的数据格式
        HashMap<String, Object> result = new HashMap<>();
        result.put("code", "200");
        result.put("msg", "");
        result.put("body", body);
        if(body instanceof String) {
            try {
                return objectMapper.writeValueAsString(result);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
